;
define("vw.dialog", ['jquery', 'bootstrap', 'select2-cn', 'bDialog', 'bootstrap.validator-cn', 'vw.static'], function() {
	"use strict";

	var defaults = {
		title: '新建',
		width: 550,
		height: 500,
		fnButtonName: "创建",
		type: 1,
		catalogID: -1,
		infourl: "",
		saveurl: "",
		paraType: 'type',
		paraCatalogID: 'catalogID',
		paraTableInfo: 'tableInfo',
		paraFiles: 'files',
		columnName: 'columns',
		dataName: 'data',
		callback: null
	};

	function vw_dialog() {
		var that = this;
		this.name = "vw_dialog";
		this.dom = '<form id="' + this.name + '-form" class="form-horizontal"></form>';
		this.open = function(opt) {
			that.options = $.extend({}, defaults, opt);
			bDialog.open({
				title: that.options.title,
				dom: that.dom,
				dialogMaxButton: false,
				customClass: 'blue',
				width: that.options.width,
				height: that.options.height,
				fnButton: that.options.fnButtonName ? true : false,
				fnButtonName: that.options.fnButtonName,
				onShow: function() {
					_datacontent(that.options.catalogID, that);
					that.$form = $('#' + that.name + '-form');
				},
				fn: function() {
					that.$form.bootstrapValidator('validate');
				},
				callback: function(data) {
					if(data.results != null) {
						if(that.options.callback) {
							that.options.callback();
						}
						var retval = data.results[0].result;
						if(data.results[0].result === true) {
							$.Notify({
								caption: "成功",
								content: that.options.fnButtonName + "成功",
								type: "success"
							});
						} else {
							$.Notify({
								caption: "错误",
								content: retval ? retval : "undefined",
								type: "alert"
							});
						}
					}
				},
			}, {
				messageType: 'confirm',
				cancel: function() {}
			});
		};
	}

	function _datacontent(catalogID, that) {
		var ajaxdata = {};
		ajaxdata[that.options.paraCatalogID] = that.options.catalogID;
		ajaxdata[that.options.paraType] = that.options.type;

		vw_common.customAjax({
			url: that.options.infourl,
			type: "GET",
			dataType: "json",
			data: ajaxdata
		}, function(e) {
			var html = '';
			var column = e[that.options.columnName];
			var data = {};
			if(e[that.options.dataName].length) {
				data = e[that.options.dataName][0];
			} else {
				for(var i = 0; i < column.length; i++) {
					data[column[i].title] = "";
				}
			}

			for(var i = 0; i < column.length; i++) {
				if(!column[i].visible) {
					continue;
				}
				html += '<div class="form-group">';
				html += '<label class="col-xs-3 control-label">' + column[i].title + ': </label>';
				var readonly = "";
				if(that.options.catalogID != -1 && column[i].disable) {
					readonly = "readonly";
				}
				if(!data[column[i].title] && column[i].defaultValue) {
					data[column[i].title] = column[i].defaultValue;
				}
				switch(column[i].type) {
					case "text":
						html += '<div class="col-xs-8">';
						html += '	<input type="text" placeholder="请输入..." class="form-control" name="' + column[i].name + '"  value="' + data[column[i].title] + '"' + readonly + '/>';
						html += '</div>';
						break;
					case "select":
						var disabled = readonly ? 'disabled' : '';
						html += '<div class="col-xs-8">';
						html += '	<select class="form-control" name="' + column[i].name + '" style="width:100%;"' + disabled + '></select>';
						html += '</div>';
						break;
					case "select2":
						html += '<div class="col-xs-7">';
						html += '	<input ids="' + data[column[i].title] + '" type="text" placeholder="请选择..." style="" class="form-control" name="' + column[i].name + '" value="' + data[column[i].title] + '" readonly /></input>';
						html += '</div>';
						html += '<button type="button" name="btn-' + column[i].name + '" class="clicks btn btn-primary" style="margin-left: -13px;"><i class="glyphicon glyphicon-list"></i></button>';
						break;
					case "file":
						html += '<div class="col-xs-6" style="padding-right:5px;width:47%">';
						html += '	<input type="text" placeholder="请选择..." style="" class="form-control" name="' + column[i].name + '" value="' + data[column[i].title] + '" readonly /></input>';
						html += '</div>';
						html += '<button type="button" name="btn-' + column[i].name + '-delete" class="clicks btn btn-danger" style="margin-right:5px"><i class="glyphicon glyphicon-trash"></i></button>';
						html += '<button type="button" name="btn-' + column[i].name + '" class="clicks btn btn-primary"><i class="glyphicon glyphicon-file"></i></button>';
						html += '<input type="file" id="' + column[i].name + '-fileimport" class="hidden" />';
						break;
					default:
				}
				html += '</div>';
			}
			that.$form.append(html);

			that.form = new FormData();

			$.each(column, function(k, val) {
				switch(val.type) {
					case "select":
						var selectVals = [];
						if(val.source) {
							$.each(val.source, function(k, v) {
								selectVals.push({
									id: v.id,
									text: v.text
								});
							});
						}
						$("select[name = '" + val.name + "']").select2({
							data: selectVals,
							placeholder: "请选择...",
							tags: true,
							language: "zh-CN",
							allowClear: true,
						});

						var curVal = data[val.title];
						$("select[name = '" + val.name + "']").val(curVal ? curVal : null).trigger('change');
						break;
					case "select2":
						var selectVals = [];
						var curText = [];
						if(val.source) {
							$.each(val.source, function(k, v) {
								selectVals.push({
									id: v.id,
									pid: v.pid,
									text: v.text
								});

								if(data[val.title].split(',').indexOf(v.id) != -1) {
									curText.push(v.text);
								}

							});
							$("input[name = '" + val.name + "']").val(curText.join(','));
						}

						$("button[name = 'btn-" + val.name + "']").on('click', function() {
							bDialog.open({
								title: '请选择',
								dom: '<input type="text" placeholder="请选择..." id="' + val.name + '-dialog-selectedval" class="form-control" readonly /></input><div id="' + val.name + '-dialog-searchtree" style="padding-top:10px"></div>',
								dialogMaxButton: false,
								customClass: 'blue',
								width: 400,
								height: 500,
								scroll: false,
								fnButton: true,
								fnButtonName: "确定",
								fn: function() {
									$("input[name = '" + val.name + "']").val(that.t.value);
									$("input[name = '" + val.name + "']").attr("ids", that.t.id);
									bDialog.close();

									if(!val.cannull) {
										//手动触发验证
										that.$form.data('bootstrapValidator')
											.updateStatus(val.name, 'NOT_VALIDATED', null)
											.validateField(val.name);
									}
								},
								params: {
									"values": selectVals,
									"currentVal": $("input[name = '" + val.name + "']").val(),
									"currentID": $("input[name = '" + val.name + "']").attr("ids")
								},
								onShow: function(dialog) {
									var $dialogSearchtree = $('#' + val.name + '-dialog-searchtree');
									var $selectedval = $('#' + val.name + '-dialog-selectedval');
									var params = dialog.params.params;
									that.t = {};
									$dialogSearchtree.vw_searchtree({
										multipleSelect: true,
										selectFirst: false,
										//selectChildNodeOnly: true,
										showSearch: false,
										height: 400,
										data: params.values,
										onTreeSelected: getValue,
										onTreeUnselected: getValue
									});

									if(params.currentID) {
										$dialogSearchtree.vw_searchtree('SelectNode', params.currentID, false);
										$selectedval.val(params.currentVal);
									}

									function getValue() {
										that.t = {
											id: [],
											value: []
										};
										$.each($dialogSearchtree.vw_searchtree('GetSelected'), function(k, v) {
											that.t.id.push(v.id);
											that.t.value.push(v.text);
										});
										$selectedval.val(that.t.value);
									}
								}
							});
						});
						break;
					case "file":
						var $fileImport = $('#' + val.name + '-fileimport');
						$("button[name = 'btn-" + val.name + "']").on('click', function() {
							$fileImport.click();
						});

						$("button[name = 'btn-" + val.name + "-delete']").on('click', function() {
							$("input[name = '" + val.name + "']").val("");
							that.form.delete(val.name);

							if(!val.cannull) {
								//手动触发验证
								that.$form.data('bootstrapValidator')
									.updateStatus(val.name, 'NOT_VALIDATED', null)
									.validateField(val.name);
							}
						});

						$fileImport.on('change', function() {
							var fileObj = $(this)[0].files[0];
							$("input[name = '" + val.name + "']").val(fileObj.name);
							that.form.append(val.name, fileObj);
							this.value = null;

							if(!val.cannull) {
								//手动触发验证
								that.$form.data('bootstrapValidator')
									.updateStatus(val.name, 'NOT_VALIDATED', null)
									.validateField(val.name);
							}
						});
						break;
					default:
				}
			});

			var fields = {};
			$.each(column, function(k, val) {
				fields[val.name] = {
					validators: {}
				};
				if(!val.cannull) {
					fields[val.name].validators.notEmpty = {
						message: val.title + '不能为空'
					}
				};
				if(val.txtformat) {
					fields[val.name].validators.regexp = {
						regexp: val.txtformat,
						message: val.txtstandard
					}
				}
			});

			_valiform(catalogID, that, fields);
		});
	}

	function _valiform(catalogID, that, fields) {
		that.$form.bootstrapValidator({
			message: '输入的内容无效',
			feedbackIcons: {
				valid: 'glyphicon glyphicon-ok',
				invalid: 'glyphicon glyphicon-remove',
				validating: 'glyphicon glyphicon-refresh'
			},
			fields: fields
		});

		that.$form.on('success.form.bv', function(e) {
			var values = {};
			var controls = that.$form.find(".form-control");
			for(var i = 0; i < controls.length; i++) {
				var filedname = $(controls[i]).attr("name");
				if($(controls[i]).attr("ids")) {
					values[filedname] = $(controls[i]).attr("ids");
				} else {
					values[filedname] = $(controls[i]).val();
				}
			}
			that.form.append(that.options.paraCatalogID, catalogID);
			that.form.append(that.options.paraType, that.options.type);
			that.form.append(that.options.paraTableInfo, JSON.stringify(values));

			vw_common.customAjax({
				url: that.options.saveurl,
				type: "POST",
				processData: false,
				contentType: false,
				dataType: "json",
				data: that.form
			}, function(e) {
				bDialog.close({
					result: e.success
				});
			}, function(err) {
				bDialog.close({
					result: err
				});
			});
		});
	}

	return function() {
		return new vw_dialog();
	}
});